<template>
  <div class="photos-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我的摄影打卡</h2>
          <el-button type="primary" @click="createPhoto">
            <el-icon><Plus /></el-icon>
            发布摄影
          </el-button>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索摄影作品"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterLocation"
          placeholder="拍摄地点"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="江滨公园" value="riverpark" />
          <el-option label="贵港博物馆" value="museum" />
          <el-option label="石龙文化园" value="shilong" />
          <el-option label="荷花公园" value="lotus" />
          <el-option label="其他景点" value="other" />
        </el-select>

        <el-select
          v-model="filterStatus"
          placeholder="作品状态"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="已发布" value="published" />
          <el-option label="待审核" value="pending" />
          <el-option label="已隐藏" value="hidden" />
        </el-select>

        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          @change="handleSortChange"
        >
          <el-option label="最新发布" value="latest" />
          <el-option label="最多点赞" value="likes" />
          <el-option label="最多收藏" value="favorites" />
          <el-option label="最多评论" value="comments" />
        </el-select>
      </div>

      <!-- 摄影作品列表 -->
      <div class="photos-list" v-loading="loading">
        <el-row :gutter="16">
          <el-col
            v-for="photo in paginatedPhotos"
            :key="photo.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            class="mb-4"
          >
            <div class="photo-card">
              <div class="photo-cover">
                <el-image
                  :src="photo.imageUrl"
                  fit="cover"
                  :preview-src-list="[photo.imageUrl]"
                  class="photo-image"
                />
                <div class="photo-actions">
                  <el-button-group>
                    <el-button type="primary" link @click="editPhoto(photo)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button type="danger" link @click="deletePhoto(photo)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </el-button-group>
                </div>
              </div>
              <div class="photo-info">
                <div class="photo-title">
                  <el-tag
                    size="small"
                    :type="getTagType(photo.status)"
                    class="mr-2"
                  >
                    {{ getStatusText(photo.status) }}
                  </el-tag>
                  {{ photo.title }}
                </div>
                <div class="photo-meta">
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ photo.location }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Camera /></el-icon>
                    <span>{{ photo.device }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDate(photo.createTime) }}</span>
                  </div>
                </div>
                <div class="photo-description">{{ photo.description }}</div>
                <div class="photo-stats">
                  <span class="stat-item">
                    <el-icon><View /></el-icon>
                    {{ photo.viewCount }}
                  </span>
                  <span class="stat-item">
                    <el-icon><ThumbUp /></el-icon>
                    {{ photo.likeCount }}
                  </span>
                  <span class="stat-item">
                    <el-icon><Star /></el-icon>
                    {{ photo.favoriteCount }}
                  </span>
                  <span class="stat-item">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ photo.commentCount }}
                  </span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && paginatedPhotos.length === 0"
          description="暂无摄影作品"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Location,
  Camera,
  Clock,
  View,
  ThumbUp,
  Star,
  ChatDotRound,
  Edit,
  Delete,
} from "@element-plus/icons-vue";
import service from "@/api/axios";

const router = useRouter();

// 状态变量
const loading = ref(false);
const searchKeyword = ref("");
const filterLocation = ref("");
const filterStatus = ref("");
const sortBy = ref("latest");
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 测试数据，API请求失败时使用
const mockPhotos = [
  {
    id: 1,
    title: "桂平西山全景",
    description: "记录桂平西山的壮丽全景，远眺西山的秀美风光...",
    imageUrl: "https://images.pexels.com/photos/2387418/pexels-photo-2387418.jpeg",
    location: "桂平西山",
    device: "Canon EOS R5",
    status: "published",
    createTime: "2025-05-10 17:30:00",
    viewCount: 356,
    likeCount: 89,
    favoriteCount: 42,
    commentCount: 16,
  },
  {
    id: 2,
    title: "贵港江滨公园夜景",
    description: "夜幕下的江滨公园灯火璀璨，江水倒映华灯，美不胜收...",
    imageUrl: "https://images.pexels.com/photos/417102/pexels-photo-417102.jpeg",
    location: "江滨公园",
    device: "Sony A7M4",
    status: "published",
    createTime: "2025-05-08 20:30:00",
    viewCount: 289,
    likeCount: 76,
    favoriteCount: 38,
    commentCount: 13,
  },
  {
    id: 3,
    title: "荷城古镇风光",
    description: "贵港荷城古镇的独特人文风光，古色古香的建筑与现代生活交融...",
    imageUrl: "https://images.pexels.com/photos/1440476/pexels-photo-1440476.jpeg",
    location: "荷城古镇",
    device: "Nikon Z7",
    status: "published",
    createTime: "2025-05-05 09:30:00",
    viewCount: 245,
    likeCount: 63,
    favoriteCount: 29,
    commentCount: 11,
  },
];

// 摄影作品列表数据
const photosList = ref([]);

// 获取摄影作品列表
const getPhotosList = async () => {
  loading.value = true;
  try {
    // 调用获取摄影作品列表API
    const response = await service.get("/user/photos", {
      params: {
        keyword: searchKeyword.value,
        location: filterLocation.value,
        status: filterStatus.value,
        sortBy: sortBy.value
      }
    });
    
    console.log("后端返回的摄影作品数据:", response);
    
    // 处理后端返回的数据
    const photosData = response && response.data ? response.data : [];
    
    if (photosData && photosData.length > 0) {
      // 处理后端返回的数据
      photosList.value = photosData.map(photo => ({
        ...photo,
        // 处理图片路径
        imageUrl: photo.imageUrl || photo.image || "/images/photos/default.jpg",
        // 确保必要字段存在
        status: photo.status || "published",
        device: photo.device || "未知设备",
        viewCount: photo.viewCount || 0,
        likeCount: photo.likeCount || 0,
        favoriteCount: photo.favoriteCount || 0,
        commentCount: photo.commentCount || 0,
        // 格式化日期(如果需要)
        createTime: photo.createTime || photo.shootTime || new Date().toISOString(),
      }));
      
      // 更新总数
      total.value = photosList.value.length;
      console.log("处理后的摄影作品数据:", photosList.value);
    } else {
      console.log("后端返回的数据为空，使用测试数据");
      // 如果后端没有数据或返回空数组，使用测试数据
      photosList.value = [...mockPhotos];
      total.value = mockPhotos.length;
    }
  } catch (error) {
    console.error("获取摄影作品列表失败:", error);
    // 出错时使用测试数据
    photosList.value = [...mockPhotos];
    total.value = mockPhotos.length;
  } finally {
    loading.value = false;
  }
};

// 计算当前页数据
const paginatedPhotos = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return photosList.value.slice(start, end);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getPhotosList();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  getPhotosList();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getPhotosList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  // 由于API不支持分页，我们在前端处理分页
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  // 由于API不支持分页，我们在前端处理分页
};

// 创建摄影作品
const createPhoto = () => {
  router.push("/photos/create");
};

// 编辑摄影作品
const editPhoto = (photo) => {
  router.push(`/photos/edit/${photo.id}`);
};

// 删除摄影作品
const deletePhoto = async (photo) => {
  try {
    await ElMessageBox.confirm("确定要删除该摄影作品吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    loading.value = true;
    
    try {
      // 调用删除摄影作品API
      await service.delete(`/user/photos/${photo.id}`);
      ElMessage.success("删除成功");
      
      // 重新获取列表
      getPhotosList();
    } catch (error) {
      console.error("API删除摄影作品失败:", error);
      
      // 模拟删除成功（仅在开发阶段使用）
      const index = photosList.value.findIndex(item => item.id === photo.id);
      if (index !== -1) {
        photosList.value.splice(index, 1);
        total.value -= 1;
      }
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除摄影作品失败:", error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取状态标签类型
const getTagType = (status) => {
  const typeMap = {
    published: "success",
    pending: "warning",
    hidden: "info",
  };
  return typeMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    published: "已发布",
    pending: "待审核",
    hidden: "已隐藏",
  };
  return textMap[status] || "未知";
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

onMounted(() => {
  getPhotosList();
});
</script>

<style lang="scss" scoped>
.photos-page {
  .page-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    :deep(.el-card__header) {
      @apply p-0 border-b border-gray-100 dark:border-gray-700;

      .card-header {
        @apply px-6 py-4 flex items-center justify-between;

        h2 {
          @apply text-lg font-medium text-gray-900 dark:text-white;
        }
      }
    }
  }

  .filter-bar {
    @apply flex items-center gap-4;

    .search-input {
      @apply w-64;
    }
  }

  .photos-list {
    .photo-card {
      @apply bg-gray-50 dark:bg-gray-800 rounded-lg overflow-hidden transition-all duration-300;

      &:hover {
        @apply shadow-lg transform -translate-y-1;

        .photo-cover {
          .photo-actions {
            @apply opacity-100;
          }
        }
      }

      .photo-cover {
        @apply relative;

        .photo-image {
          @apply w-full aspect-[4/3] object-cover;
        }

        .photo-actions {
          @apply absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 transition-opacity duration-300;
        }
      }

      .photo-info {
        @apply p-4;

        .photo-title {
          @apply flex items-center text-gray-900 dark:text-white font-medium mb-2;
        }

        .photo-meta {
          @apply flex flex-wrap gap-3 text-sm text-gray-500 dark:text-gray-400 mb-2;

          .meta-item {
            @apply flex items-center;

            .el-icon {
              @apply mr-1;
            }
          }
        }

        .photo-description {
          @apply text-sm text-gray-600 dark:text-gray-300 mb-3 line-clamp-2;
        }

        .photo-stats {
          @apply flex items-center justify-between text-sm text-gray-500 dark:text-gray-400;

          .stat-item {
            @apply flex items-center;

            .el-icon {
              @apply mr-1;
            }
          }
        }
      }
    }
  }

  .pagination-wrapper {
    @apply flex justify-center mt-6;
  }
}
</style>
